package com.example.myapplication;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileDemoActivity extends AppCompatActivity {
    private EditText input;
    private Button buttonWrite;
    private Button buttonRead;
    private CheckBox checkBoxAppend;
    private TextView textViewContent;
    private TextView textViewInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file_demo);
        input = findViewById(R.id.editText_input);
        buttonWrite = findViewById(R.id.button_write);
        buttonRead = findViewById(R.id.button_read);
        checkBoxAppend = findViewById(R.id.checkbox_append);
        textViewContent = findViewById(R.id.textView_content);
        textViewInfo = findViewById(R.id.textView_info);

        buttonWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    writeToFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        buttonRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    readFromFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void writeToFile() throws IOException {
        String fileName = "fileDemo.txt";
        FileOutputStream out = null;
        if (checkBoxAppend.isChecked()) {
            out = openFileOutput(fileName, Context.MODE_APPEND);
        } else {
            out = openFileOutput(fileName, Context.MODE_PRIVATE);
        }
        String content = input.getText().toString();
        out.write(content.getBytes());
        out.flush();
        out.close();

        textViewInfo.setText("文件写入成功，写入长度：" + content.length());
        input.setText("");
    }

    private void readFromFile() throws IOException {
        String fileName = "fileDemo.txt";
        FileInputStream in = openFileInput(fileName);
        byte[] data = new byte[in.available()];
        while (in.read(data) != -1) {
            textViewContent.setText(new String(data));
        }
        textViewInfo.setText("文件读取成功");
        in.close();
    }
}
